#!/usr/bin/env python
# coding=utf-8

import unittest
import time
from utility import app
from utility.type import *


def add_project_path_to_search_path():
    import sys
    import os.path
    project_dir = os.path.abspath(os.path.join(__file__, '../..'))
    if project_dir not in sys.path:
        sys.path.append(project_dir)

add_project_path_to_search_path()

class BaseTests():
    @classmethod
    def setUpClass(cls, setFlag=False):
        from utility import app
        cls.driver = app.start_app(setFlag)

    def __init__(self, assertTestCase):
        self.assertFunc = assertTestCase

    def setUp(self):
        self._permit_note_if_exists()
        time.sleep(2)

    def hide_keyboard(self):
        self.driver.tap([(50, 50)])

    def tap_tab_index(self, idx):
        """
        :param idx: idx begins with 0.
        """
        size_dict = self.driver.get_window_size()
        w, h = size_dict['width'], size_dict['height']
        tab_count = 5
        tab_center_x = (w / tab_count)*(idx + 0.5)
        tab_height = 49.0
        tab_center_y = (h - tab_height) + 0.5*tab_height
        self.driver.tap([(tab_center_x, tab_center_y)])

    def _permit_note_if_exists(self):
        ele = self.driver.find_element_by_ios_predicate(u'name CONTAINS "通知"')
        if not ele: return

        ele = self.driver.find_element_by_ios_predicate(u'name CONTAINS "允许"')
        if not ele: return
        # self.assertFunc.assertIsNotNone(ele, u'`通知`弹窗 应该含有 [允许] 按钮')
        ele.click()


    def logout(self):
        # 进入我tab
        self.tap_tab_index(4)
        time.sleep(1)
        # 点击设置按钮
        PK = self.driver.find_element_by_xpath(u'//XCUIElementTypeStaticText[@name="PK胜利"]').text
        self.assertFunc.assertEqual(PK, u'PK胜利', '【APP】>>>>没有找到个人信息‘pk胜利’ 进入失败')
        self.driver.tap([(381, 37)], 10)
        time.sleep(2)

        # 点击退出账号
        lgout = self.driver.find_element_by_xpath(u'//XCUIElementTypeApplication[@name="作业盒子小学"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeTable/XCUIElementTypeCell[12]')
        lgout.click()

        # 弹出确认退出弹窗
        lgout_sure = self.driver.find_element_by_xpath(u'//XCUIElementTypeButton[@name="确定"]')
        self.assertFunc.assertIsNotNone(lgout_sure, u'登录界面必须有 [确认] 按钮')
        lgout_sure.click()

        time.sleep(1)

    def login(self, mobile='18210817745', password='123456'):
        time.sleep(5)

        self._permit_note_if_exists()
        time.sleep(1)
        login_btn = self.driver.find_element_by_ios_predicate(u'name MATCHES "登.*?录"')
        if not login_btn: return
        # self.assertFunc.assertIsNotNone(login_btn, u'登录界面必须有 [登录] 按钮')
        login_btn.click()

        time.sleep(2)

        mobile_field = self.driver.find_element_by_class_name(ElementType.TextField)
        passwd_field = self.driver.find_element_by_class_name(ElementType.SecureTextField)
        mobile_cancle = self.driver.find_element_by_xpath(u'//XCUIElementTypeButton[@name="icon clearBtn"]')

        if mobile_cancle:mobile_cancle.click()

        if not mobile_field:
            print (u'必须要有手机号输入框')
            return
        if not passwd_field:
            print(u'必须要有密码输入框')
            return

        mobile_field.send_keys(mobile)
        passwd_field.send_keys(password)

        self.hide_keyboard()

        login_btn = self.driver.find_element_by_ios_predicate(u'name LIKE "登*录"')
        if not login_btn:
            print(u'登录界面必须有 [登录] 按钮（输入账号页面）')
            return
        login_btn.click()
        #等待开屏页过去
        time.sleep(4)
        homework_list_title = self.driver.find_element_by_xpath(u'//XCUIElementTypeStaticText[@name="作业本"]').text
        if homework_list_title == u'作业本':
            print '【APP】>>>>定位到作业列表不用查找弹窗'
        else:
            self.login_popwindow()

    def login_popwindow(self):
        for index in range(1,9):
            login_grade = self.driver.find_element_by_xpath(u'//XCUIElementTypeButton[@name="一年级"]')
            login_grade_sure = self.driver.find_element_by_xpath(u'//XCUIElementTypeButton[@name="确 定"]')
            login_popwindow_cancle = self.driver.find_element_by_xpath(u'//XCUIElementTypeButton[@name="close gray x"]')
            login_signin_cancle = self.driver.find_element_by_xpath(u'//XCUIElementTypeButton[@name="signIn main closeBtn"]')
            login_bugbookcard_sure = self.driver.find_element_by_xpath(u'//XCUIElementTypeButton[@name="立即领取"]')
            login_updateapp_cancel = self.driver.find_element_by_ios_predicate(u'name CONTAINS "暂不升级"')
            login_vip_overtime = self.driver.find_element_by_ios_predicate(u'name CONTAINS "VIP已到期"')

            if login_grade and login_grade_sure:
                login_grade_sure.click()
                print '【APP】>>>>循环第',index,'次,用户首次登录选择布克阅读默认年级，选择一年级并点击关闭'
            elif login_updateapp_cancel:
                login_updateapp_cancel.click()
                print '【APP】>>>>循环第',index,'次,关闭升级弹窗'
            elif login_popwindow_cancle:
                login_popwindow_cancle.click()
                print '【APP】>>>>循环第',index,'次,popwindow商业化弹窗，点击关闭按钮'
            elif login_vip_overtime:
                self.driver.tap([(156, 30)], 10)
                print '【APP】>>>>循环第',index,'次,会员过期弹窗出现，点击任意位置让弹窗消失'
            elif login_signin_cancle:
                login_signin_cancle.click()
                print '【APP】>>>>循环第',index,'次,【APP】签到弹窗出来了，点击关闭按钮'
            elif login_bugbookcard_sure:
                login_bugbookcard_sure.click()
                print '【APP】>>>>循环第',index,'次,【APP】学习卡购买弹窗，点击并领取'
            else:
                print '【APP】>>>>循环第',index,'次,当前页面没有找到任何启动弹出弹窗'
            index += 1

    #作业列表上拉刷新找可以做大的日常作业
    def homework_list(self,max_swipe_times):
        print '【APP】>>>>'

        table = self.driver.find_element_by_class_name(ElementType.Table)
        self.assertFunc.assertIsNotNone(table, u"没有页面元素")

        cells = table.find_elements_by_class_name(ElementType.Cell)
        self.assertFunc.assertNotEqual(len(cells), 0, u'作业列表为空')

        time.sleep(1)

        idx, btn = self.find_cell_with_unanswered_queston(table,max_swipe_times)

        if btn:
            self.swipeScreen(0.5,0.29,0.5,0.28)
            btn.click()
            print '【APP】>>>>点击',btn,'按钮'
        else:
            print '【APP】>>>>上拉 %d 次，还是没找到答题按钮' % max_swipe_times
            return

        time.sleep(0.5)
        # 提示有新题型需要APP升级
        upadte_version = self.driver.find_element_by_ios_predicate(u'name CONTAINS "确认"')
        if upadte_version:
            upadte_version.click()
            print '【APP】>>>>点击解答按钮返回了20073提示升级APP，需要打一个版本号比较高的包进行验证'

        time.sleep(1)
        draft_book = self.driver.find_element_by_xpath(u'//XCUIElementTypeButton[@name="草稿本"]')
        self.assertFunc.assertIsNotNone(draft_book, u'应该有草稿本按钮但是没有')
        print '【APP】>>>>正确进入作答场景'


    # 定义屏幕的宽高
    def getScreenSize(self):
        x = self.driver.get_window_size()['width']
        y = self.driver.get_window_size()['height']
        return x, y

    #按比例滑动屏幕
    def swipeScreen(self, startx_bili=0.5, starty_bili=0.75, endx_bili=0.5, endy_bili=0.5):
        x = self.getScreenSize()[0]
        y = self.getScreenSize()[1]
        self.driver.swipe(int(x * startx_bili), int(y * starty_bili), int(x * endx_bili), int(x * endy_bili))
        print '【APP】>>>>滑动屏幕从坐标(', x*startx_bili, y*starty_bili, '）到（', x*endx_bili, y*endy_bili,'）'

        time.sleep(1)
        homework_list_title = self.driver.find_element_by_xpath(u'//XCUIElementTypeStaticText[@name="作业本"]').text
        self.assertFunc.assertEqual(homework_list_title, u'作业本', '【APP】>>>>没有找到作业列表标题栏，返回作业列表失败')


    def find_cell_with_unanswered_queston(self,table, max_swipe_times, from_index = 0):
        idx, btn = -1, None

        if max_swipe_times < 0:
            return idx, btn

        cells = table.find_elements_by_class_name(ElementType.Cell)

        # 遍历作业列表知道找到可以点击的解答/补交按钮后进入
        for index in range(from_index, max_swipe_times):
            print '【APP】>>>>遍历作业列表寻找可显示解答按钮'

            cell = cells[index]
            cell_size = cell.size['height']

            # 滑动屏幕找到cell的坐标
            end_location_x = cells[index].location['x']
            end_location_y = cells[index].location['y'] + int(cell_size) # xy是全屏幕的由于底部有标题栏 增加一个标题栏的高度为了让最后一个cell的按钮可见
            start_location_x = cells[index-1].location['x']
            start_location_y = cells[index-1].location['y']

            # 当cell不展示屏幕内时，滑动屏幕直到找到可以cell的返回未true可展示状态
            while not cell.is_displayed():
                print '【APP】>>>>使用找cell的是都显示来找按钮是否可以点击'
                self.driver.swipe(start_location_x, start_location_y, end_location_x, end_location_y+64)
                time.sleep(0.2)
                print '【APP】>>>>从(',start_location_x,start_location_y,')到(',end_location_x,end_location_y,')'

            btn = cell.find_element_by_class_name(ElementType.Button)
            cananswer_jieda = self.driver.find_element_by_ios_predicate(u'name CONTAINS "解答"')
            cananswer_bujiao = self.driver.find_element_by_ios_predicate(u'name CONTAINS "补交"')

            # python 三目运算符 当btn 课条件同时成立是exist_answer_btn为true否则是false
            exist_answer_btn = True if btn and (btn.text == u'补交' or btn.text == u'解答' or cananswer_jieda or cananswer_bujiao) else False
            if exist_answer_btn:
                idx, btn = index, btn
                break
            if index == max_swipe_times:
                print '【APP】>>>>找了',index,'次，没找到显示的按钮'
                continue
            else:
                self.swipeScreen()

        if not btn:
            self.swipeScreen()
            print '【APP】>>>>划一划',index
            return self.find_cell_with_unanswered_queston(table, max_swipe_times - 1, len(cells))
        if btn.text == u'参加比赛':
            return self.find_cell_with_unanswered_queston(table, max_swipe_times - 1, len(cells))
        else:
            print '【APP】>>>>找到可以点击按钮', btn.text
            return idx, btn

    #作业结果页关闭所有弹窗后回到作业列表
    def result_dismiss_popwindow(self):
        #提交完毕，查看是否进入作业概览页
        time.sleep(1)
        match_result_title = self.driver.find_element_by_xpath(u'//XCUIElementTypeStaticText[@name="作业概览"]').text
        self.assertFunc.assertEqual(match_result_title, u'作业概览', '【APP】>>>>没有进入作业概览页，提交失败')

        #循环找弹窗知道关闭所有弹窗
        for result_popwindow_number in range(0,5):
            close_result_popwindow_integral = self.driver.find_element_by_xpath(u'//XCUIElementTypeButton[@name="close bold x"]')
            close_result_popwindow_guide = self.driver.find_element_by_xpath(u'//XCUIElementTypeButton[@name="ktmath exercise popup close no"]')

            if close_result_popwindow_integral:
                close_result_popwindow_integral.click()
                print '【APP】>>>>作业结果页关闭积分弹窗'

            elif close_result_popwindow_guide:
                close_result_popwindow_guide.click()
            else:
                print result_popwindow_number,'积分弹窗', close_result_popwindow_integral
                print result_popwindow_number,'同步练引导', close_result_popwindow_guide
                break

            result_popwindow_number += 1

        #点击返回按钮 回到作业列表
        time.sleep(1)
        match_result_backbutton = self.driver.find_element_by_xpath(u'//XCUIElementTypeButton[@name="sumerHoliday nav back"]')
        if match_result_backbutton:
            match_result_backbutton.click()
        else:
            self.driver.tap([(19, 40)], 10)
        #提交完毕，回到作业列表断言
        time.sleep(1)
        homeworklist_title = self.driver.find_element_by_xpath(u'//XCUIElementTypeStaticText[@name="作业本"]').text
        self.assertFunc.assertEqual(homeworklist_title, u'作业本', '没有进入作业列表，提交失败')

    #按名字查找可做的作业
    def find_name_with_unanswered_queston(self,max_swipe_times,from_index=0):
        index, btn = -1, None
        for index in range(from_index, max_swipe_times):
            print '【APP】>>>>找作业按钮名字遍历作业列表寻找可显示解答按钮'

            if self.driver.find_element_by_ios_predicate(u'name CONTAINS "解答"'):
                btn = self.driver.find_element_by_ios_predicate(u'name CONTAINS "解答"')
                print '【APP】>>>>找到解答按钮'
                return index, btn
            elif self.driver.find_element_by_ios_predicate(u'name CONTAINS "补交"'):
                btn = self.driver.find_element_by_ios_predicate(u'name CONTAINS "补交"')
                print '【APP】>>>>找到补交按钮'
                return index, btn
            else:
                self.swipeScreen()
        return index,btn